# -*- coding: utf-8 -*-
"""
Created on Fri Nov 10 13:20:35 2017

@author: za-xuzhaoye
"""

import csv
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller,coint
import statsmodels.api as sm
import seaborn as sns

def testStationarity(data):
    adftest = adfuller(data)
    result = pd.Series(adftest[0:4], index=['Test Statistic','p-value','Lags Used','Number of Observations Used'])
    for key,value in adftest[4].items():
        result['Critical Value (%s)'%key] = value
    return result

#读取数据
with open('D:\FOF_strategy\A&H_ETF_data\ClosePrice.csv','rb') as csvfile:
    reader=csv.DictReader(csvfile)
    H_ETF = [row['H_ETF'] for row in reader]  
    float_H_ETF=[float(x) for x in H_ETF]
    hetf1=pd.Series(float_H_ETF,index=range(len(float_H_ETF)))

with open('D:\FOF_strategy\A&H_ETF_data\ClosePrice.csv','rb') as csvfile:
    reader=csv.DictReader(csvfile)
    SZETF = [row['50ETF'] for row in reader]
    float_SZETF=[float(x) for x in SZETF]
    szetf1=pd.Series(float_SZETF,index=range(len(float_SZETF)))

#检验数据平稳性    
    hetf=np.array(hetf1)
    szetf=np.array(szetf1)
#    hetf=hetf.T[0];
#    szetf=szetf.T[0]
    zz=pd.concat([testStationarity(hetf),testStationarity(szetf)],axis=1)
    zz.columns=['hetf','szetf']
    
  #一价差分，再验平稳性  
    diff_hetf = hetf1.diff(1)
    diff_hetf.dropna(inplace=True)
    diff_hetf=np.array(diff_hetf)
    
    diff_szetf = szetf1.diff(1)
    diff_szetf.dropna(inplace=True)
    diff_szetf=np.array(diff_szetf)
    tz=pd.concat([testStationarity(diff_hetf),testStationarity(diff_szetf)],axis=1)
    tz.columns=['hetf','szetf']
    
    coint_test= coint(szetf,hetf)[1]
    
    mean=(szetf1-hetf1).mean()
    std=(szetf1-hetf1).std()
    up=mean+std
    down=mean-std
    s1=pd.Series(mean,index=range(len(hetf)))
    up_line=pd.Series(up,index=range(len(hetf)))
    down_line=pd.Series(down,index=range(len(hetf)))
    data3=pd.concat([szetf1-hetf1,s1,up_line,down_line],axis=1)
    data3.columns=['spreadprice','mean','upper','down']
    print up,down

    data3.plot(figsize=(14,7))
    
    